<?php

namespace app\api\controller;


use app\admin\model\BuildingZoneModel;
use app\common\controller\Api;


class Zone extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * @var BuildingZoneModel
     */
    protected $model = null;

    protected $user_id = 0;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new BuildingZoneModel();
        $this->user_id = $this->auth->id;
    }

    public function index()
    {
        $kw = $this->request->param('kw');
        $where = [];
        if (!empty($kw)) {
            $where['name'] = ['like', '%' . $kw . '%'];
        }
        $list = $this->model
            ->where("find_in_set($this->user_id,user_id)")
            ->where($where)
            ->field('id,name')
            ->select();

        $this->success('请求成功', $list);
    }

    public function add()
    {
        $params = $this->request->param();
        if (empty($params['name'])) {
            $this->error('名称不能为空');
        }
        $params['user_id'] = $this->user_id;
        $res = BuildingZoneModel::create($params, true);
        if ($res) {
            $this->success('成功');
        } else {
            $this->error('失败');
        }

    }

    public function edit()
    {
        $id = $this->request->param('id/d');
        $name = $this->request->param('name');
        if (empty($name)) {
            $this->error('名称不能为空');
        }

        $row = $this->model::get($id);
        if (!$row) {
            $this->error('数据不存在');
        }

        $row->name = $name;
        $row->save();
        $this->success('成功');
    }

    public function del()
    {
        $id = $this->request->param('id/d');

        $row = $this->model::get($id);
        if (!$row) {
            $this->error('数据不存在');
        }

        $row->delete();
        $this->success('成功');
    }


}
